package com.example.system.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.system.tools.ResultHelper;
import com.example.system.tools.ValidatedGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

/**
 * @PackageName: com.community.framework.system.base
 * @ClassName： BaseController
 * @Description： 扩展基础控制器
 * @Author： tracy
 * @Date： 2019/5/6 14:13
 * @Version: 1.0
 **/
public class ExpandBaseController<T extends BaseEntity> extends BaseController {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected IService<T> service;

    /**
     * @Description: 单表通用分页查询
     * @Author: tracy
     * @CreateTime: 17:42
     * @Version: 1.0
     *
     * @param page   分页查询
     * @param entity 查询实体
     * @return
     */
    @GetMapping("/page")
    public ResultHelper singleTablePaging(Page<T> page, T entity) {
        if (page.descs() == null || page.descs().length == 0) {
            page.setDesc("create_time");
        }
        IPage<T> result = service.page(page, new QueryWrapper<>(entity));
        try {
            return ResultHelper.success(new CustomHashMap()
                    .put("pageNo", result.getCurrent())
                    .put("pageSize", result.getSize())
                    .put("totalCount",result.getTotal())
                    .put("totalPage", result.getPages())
                    .put("data",result.getRecords()));
        } catch (Exception e) {
            logger.error("分页查询失败, URL={}, error={}", request.getRequestURI(), e);
            e.printStackTrace();
            return ResultHelper.fail("查询失败！");
        }
    }

    /**
     * @Description: 单表通用数据集查询，查询所有数据列表
     *                      查询所有数量不能超过100条
     * @Author: tracy
     * @CreateTime: 17:43
     * @Version: 1.0
     * 单表通用数据集查询
     *
     * @param entity 查询实体
     * @param isAcs
     * @param order
     * @return
     */
    @GetMapping("/list")
    public ResultHelper list(T entity, Boolean isAcs, String... order) {
        QueryWrapper wrapper = new QueryWrapper(entity);
        if (isAcs != null) {
            wrapper.orderBy(true, isAcs, order);
        }
        try {
            List<T> list = service.list(wrapper);
            return ResultHelper.success(list);
        } catch (Exception e) {
            logger.error("分页查询失败, URL={}, ERROR={}", request.getRequestURI(), e);
            e.printStackTrace();
            return ResultHelper.fail("查询失败！");
        }

    }

    /**
     * @Description: 根据主键查询唯一数据
     * @Author: tracy
     * @CreateTime: 17:53
     * @Version: 1.0
     *
     * @param id 主键
     * @return
     */
    @GetMapping("/getById/{id}")
    public ResultHelper selectOneById(@PathVariable Serializable id) {
        try {
            return ResultHelper.success(service.getById(id));
        } catch (Exception e) {
            logger.error("分页查询失败, URL={},ID = {}, ERROR={}", request.getRequestURI(), id, e);
            e.printStackTrace();
            return ResultHelper.fail("查询失败！");
        }
    }

    /**
     * 单个实体保存
     * @param entity 实体
     * @return 响应封装
     */
    @Deprecated
    @PostMapping("/save")
    public ResultHelper save(@RequestBody @Validated(value = { ValidatedGroup.Add.class, ValidatedGroup.Default.class }) T entity, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            String errMsg = bindingResult.getFieldError().getDefaultMessage();
            return ResultHelper.fail(errMsg);
        }
        entity.setCreator("testCreator");
        return ResultHelper.success(service.saveOrUpdate(entity));
    }
    /**
     * 单个实体保存
     * @param entity 实体
     * @return 响应封装
     */
    @PostMapping("/insert")
    public ResultHelper insert(@RequestBody @Validated(value = { ValidatedGroup.Add.class, ValidatedGroup.Default.class }) T entity, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            String errMsg = bindingResult.getFieldError().getDefaultMessage();
            return ResultHelper.fail(errMsg);
        }
        entity.setCreator("testCreator");
        return ResultHelper.success(service.save(entity));
    }
    /**
     * 根据主键修改实体属性
     * @param entity 实体
     * @return 响应封装
     */
    @PostMapping("/update")
    public ResultHelper updateById(@RequestBody @Validated(value = { ValidatedGroup.Update.class, ValidatedGroup.Default.class }) T entity, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            String errMsg = bindingResult.getFieldError().getDefaultMessage();
            return ResultHelper.fail(errMsg);
        }
        entity.setModifier("testModifier");
        entity.setModifyTime(new Timestamp(System.currentTimeMillis()));
        return ResultHelper.success(service.updateById(entity));
    }
    /**
     * @Description: 根据主键删除数据（逻辑删除，因加了一个逻辑删除插件）
     * @Author: tracy
     * @CreateTime: 17:51
     * @Version: 1.0
     *
     * @param id
     * @return
     */
    @GetMapping("/deleteById/{id}")
    public ResultHelper deleteById(@PathVariable Serializable id) {
        try {
            return ResultHelper.success("删除成功", service.removeById(id));
        } catch (Exception e) {
            logger.error("分页查询失败，URL={}, ID = {}, ERROR={}", request.getRequestURI(), id, e);
            e.printStackTrace();
            return ResultHelper.fail("删除失败！");
        }
    }

    /**
     * @Description: 批量删除数据，根据IDS
     * @Author: tracy
     * @CreateTime: 17:54
     * @Version: 1.0
     *
     * @param ids
     * @return
     */
    @GetMapping("/batchDeleteByIds")
    public ResultHelper batchDelete(String... ids) {
        try {
            return ResultHelper.success(service.removeByIds(Arrays.asList(ids)));
        } catch (Exception e) {
            logger.error("分页查询失败，URL={}, IDS = {}, ERROR={}", request.getRequestURI(), ids, e);
            e.printStackTrace();
            return ResultHelper.fail("批量删除失败！");
        }
    }
}
